﻿var status = require('http-status');
var User = require('../models/user');

var express = require('express');
var router = express.Router();

router.post('/', function (req, res) {
    var _user = req.body.user || {};
    var _username = _user.username;
    if (!_username) {
        return res.status(status.BAD_REQUEST).json({error: 'Invalid User Info'});
    }
    else {
        User.findOne({username: _username}, function (err, user) {
            if (err) {
                return res.status(status.INTERNAL_SERVER_ERROR);
            }
            if (user) {
                return res.status(status.CONFLICT).json({error: 'User Already Existed'});
            } else {
                User.create(_user, function (err, user) {
                    if (err) {
                        return res.status(status.BAD_REQUEST).json({error: 'Invalid User Info'});
                    }
                    return res.status(status.CREATED).json({user: user.tidyInfo()});
                });
            }
        });
    }
});

router.put('/', function (req, res) {
    if (!req.user) {
        return res.status(status.UNAUTHORIZED).end();
    }
    var _user = req.body.user || {};
    req.user.password = _user.password || req.user.password;
    req.user.subject = _user.subject || req.user.subject;
    req.user.save(function (err) {
        if (err) {
            return res.json(status.BAD_REQUEST, {error: 'Invalid User Info'});
        }
        res.status(status.OK).json({user: req.user.tidyInfo()});
    });
});

router.get('/', function (req, res) {
    if (!req.user) {
        return res.status(status.UNAUTHORIZED).end();
    }
    res.json({user: req.user.tidyInfo()});
});

router.get('/:name', function (req, res) {
    if (!req.user) {
        return res.status(status.UNAUTHORIZED).end();
    }
    User.findOne({username: req.params.name}, function (err, user) {
        if (err) {
            return res.status(status.INTERNAL_SERVER_ERROR).end();
        }
        if (!user) {
            return res.status(status.NOT_FOUND).json({error: 'User Not Found'});
        } else {
            return res.status(status.OK).json({user: user.tidyInfo()});
        }
    });
});

module.exports = router;